package com.camera.yl.fragment

import com.camera.base.BaseApp
import com.camera.base.v.BaseFragment
import com.camera.base.v.GridSpacingItemDecoration
import com.camera.yl.R
import com.camera.yl.adapter.SubMenuAdapter
import com.camera.yl.bean.MenuItemInfo
import com.camera.yl.databinding.FragmentLocalBinding
import com.camera.yl.v.MainActivity

class LocalFragment : BaseFragment<FragmentLocalBinding>() {
    private lateinit var itemsList: MutableList<MenuItemInfo>
    private lateinit var mAdapter: SubMenuAdapter
    override fun loadData(isRefresh: Boolean) {
        prepareData()
        initAdapter()
    }

    override fun initView() {
        // 通过数据绑定设置标题
        mBinding.fragmentTitle = getString(R.string.camera_fragment)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_local
    }
    private fun initAdapter() {
        if(itemsList!!.size <= 0) return
        val spanCount = 3
        val mGridLayoutManager = androidx.recyclerview.widget.GridLayoutManager(
            mContext,
            spanCount
        )
        
        // 设置SpanSizeLookup确保每个项目占据相同的空间
        mGridLayoutManager.spanSizeLookup = object : androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return 1 // 每个项目占据1个空间单位
            }
        }
        
        mBinding.rvFragmentLoclHome.layoutManager = mGridLayoutManager
        
        // 添加网格间距装饰器
        val spacing = resources.getDimensionPixelSize(com.camera.base.R.dimen.qb_px_16) // 16dp的间距
        mBinding.rvFragmentLoclHome.addItemDecoration(GridSpacingItemDecoration(spanCount, spacing, true))
        
        //这里用线性宫格显示 类似于grid view
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mBinding.rvFragmentLoclHome.setHasFixedSize(true)
        mAdapter = SubMenuAdapter(mContext, itemsList)
        mBinding.rvFragmentLoclHome.adapter = mAdapter
        mAdapter.setClickListener { view, position ->
            val subMenu: MenuItemInfo = itemsList.get(position)
            (mContext as MainActivity).onSelectMenuItem(subMenu)
        }
    }

    private fun prepareData() {
        val items = BaseApp.ylBean.items.split(",".toRegex()).toTypedArray()
        itemsList = ArrayList<MenuItemInfo>()
        var itemInfoM: MenuItemInfo? = null
        for (name in items) {
            if (name == "video") {
                itemInfoM = MenuItemInfo(getString(R.string.camera_fragment), R.drawable.ic_video, "video")
            }  else if (name == "file") {
                itemInfoM = MenuItemInfo(getString(R.string.file_fragment), R.drawable.ic_folder, "file")
            }

            if (itemInfoM != null) {
                itemsList?.add(itemInfoM!!)
                itemInfoM = null
            }
        }
    }
}